<!--
 * @Description: 全局搜索组件
 *
-->
<template>
  <!-- 搜索触发器 -->
  <div
    class="flex h-8 items-center gap-3 rounded-2xl px-2 py-0.5 cursor-pointer transition-all-300 bg-[var(--el-fill-color-light)]"
    @click="toggleOpen"
  >
    <Icon
      icon="material-symbols:search"
      class="text-gray-400 group-hover:text-primary transition-all-300 font-size-5"
    />
    <span
      class="text-gray-400 group-hover:text-primary hidden text-xs transition-all-300 md:block font-size-3.5"
    >
      搜索
    </span>
    <span
      v-if="enableShortcutKey"
      class="hidden md:flex items-center text-xs text-gray-400 group-hover:text-primary bg-gray-100 dark:bg-gray-800 px-1.5 py-1 rounded"
    >
      {{ isWindows ? "Ctrl" : "⌘" }}
      <span class="ml-1">K</span>
    </span>
  </div>
  <!-- 搜索弹框 -->
  <el-dialog
    v-model="isOpen"
    width="500px"
    :fullscreen="isMobile"
    :center="true"
    :show-close="false"
    class="search-dialog flex flex-col p-0"
    @closed="handleClose"
  >
    <!-- 搜索头部 -->
    <template #header="{ close }">
      <div class="flex items-center border-b border-gray-200 p-y-3 p-x-3">
        <Icon
          icon="material-symbols:search"
          class="text-gray-400 mr-2 text-lg w-6 h-6"
        />
        <input
          ref="searchInputRef"
          v-model="searchKeyword"
          placeholder="搜索菜单..."
          class="w-full bg-transparent border-none outline-none text-sm p-2 pl-0 font-size-4"
          @keydown.esc="handleClose"
        />
        <Icon class="w-6 h-6" icon="ep-close" @click="close"></Icon>
      </div>
    </template>
    <!-- 搜索面板 -->
    <div class="flex flex-1 wh-full justify-center p-x-2">
      <!-- 无搜索结果 -->
      <div
        v-if="searchKeyword && searchResults.length === 0"
        class="text-muted-foreground text-center"
      >
        <Icon icon="material-symbols:search-off" class="mx-auto mt-4 size-12" />
        <p class="mb-10 mt-6 text-xs font-size-3.2">
          暂无搜索结果
          <span class="text-foreground text-sm font-medium">
            "{{ searchKeyword }}"
          </span>
        </p>
      </div>
      <!-- 历史搜索记录 & 没有搜索结果 -->
      <div
        v-if="!searchKeyword && searchResults.length === 0"
        class="text-muted-foreground text-center"
      >
        <p class="my-10 text-xs">暂无搜索结果</p>
      </div>

      <ul v-else-if="searchResults.length > 0" class="w-full">
        <li
          v-for="item in searchResults"
          :key="item.path"
          class="flex-center mb-3 w-full cursor-pointer rounded-lg px-4 py-4 hover:bg-[var(--el-color-primary-light-8)]"
          @click="handleClickSearch(item)"
        >
          <Icon :icon="item.meta?.icon" class="mr-2 size-5 flex-shrink-0" />
          <span class="flex-1">{{ item.meta?.title }}</span>
        </li>
      </ul>
    </div>
    <!-- 搜索底部 -->
    <template #footer>
      <div
        class="flex w-full justify-start text-xs text-gray-500 border-t border-color-[var(border-gray-600)] p-y-4"
      >
        <div class="mr-4 flex items-center">
          <Icon icon="material-symbols:keyboard-return" class="mr-1 size-4.5" />
          选择
        </div>
        <div class="mr-4 flex items-center">
          <Icon
            icon="material-symbols:keyboard-arrow-up"
            class="mr-1 size-4.5"
          />
          <Icon
            icon="material-symbols:keyboard-arrow-down"
            class="mr-1 size-4.5"
          />
          导航
        </div>
        <div class="flex items-center">
          <Icon icon="material-symbols:keyboard-escape" class="mr-1 size-4.5" />
          关闭
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import routes from "@/router/routes";
const router = useRouter();
const appSetting = useAppSetting();
const isMobile = computed(() => appSetting.isMobile);

const props = withDefaults(
  defineProps<{
    enableShortcutKey?: boolean;
  }>(),
  {
    // 是否显示快捷键
    enableShortcutKey: true,
  }
);

const isOpen = ref(false);
const searchKeyword = ref("");
const searchInputRef = ref<HTMLInputElement>();
const isWindows = navigator?.platform.includes("Win"); // 此处语法已被启用
// 搜索结果
const searchResults = computed(() => {
  if (!searchKeyword.value) return [];
  return routes.filter(
    (route) =>
      (!route.meta?.hidden &&
        route.name &&
        route.name.toString().includes(searchKeyword.value)) ||
      (route.meta?.title &&
        route.meta.title.toString().includes(searchKeyword.value))
  );
});
// 搜索结果点击
const handleClickSearch = (item: RouteRecordRaw) => {
  router.push(item.path);
  isOpen.value = false;
};

// 打开/关闭搜索
const toggleOpen = () => {
  isOpen.value = !isOpen.value;
  if (isOpen.value) {
    nextTick(() => {
      searchInputRef.value?.focus();
    });
  }
};

// 关闭搜索
const handleClose = () => {
  isOpen.value = false;
  searchKeyword.value = "";
};

// 快捷键处理
const keys = useMagicKeys();
const searchHotkey = computed(() =>
  isWindows ? keys["ctrl+k"] : keys["meta+k"]
);

watch(searchHotkey, (v) => {
  if (v && props.enableShortcutKey) {
    toggleOpen();
  }
});

// 阻止浏览器默认搜索快捷键
const preventDefaultSearch = (e: KeyboardEvent) => {
  if ((e.key === "k" || e.key === "K") && (e.metaKey || e.ctrlKey)) {
    e.preventDefault();
  }
};

onMounted(() => {
  if (props.enableShortcutKey) {
    window.addEventListener("keydown", preventDefaultSearch);
  }
});

onUnmounted(() => {
  window.removeEventListener("keydown", preventDefaultSearch);
});
</script>

<style lang="less">
.search-dialog {
  .el-dialog__body {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
</style>
